package stark.app.function.news;

import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import stark.app.R;
import stark.app.databinding.FragmentNewsListBinding;
import stark.common.apis.base.NewsBean;
import stark.common.apis.constant.NewsType;
import stark.common.basic.adaptermutil.StkLoadDataCallback;
import stark.common.basic.base.BaseNoModelFragment;

/**
 * Author：daizhongbin on 2022/12/1
 * Email：1027154338@qq.com
 * Desc:
 */
public class NewsListFragment extends BaseNoModelFragment<FragmentNewsListBinding> {

    private NewsType mNewsType;
    private NewsAdapter mNewsAdapter;
    private boolean isRefresh = false;

    public NewsListFragment(NewsType type) {
        mNewsType = type;
    }

    @Override
    protected int onCreate() {
        return R.layout.fragment_news_list;
    }

    @Override
    protected void initView() {
        mDataBinding.rvNews.setLayoutManager(new LinearLayoutManager(getContext()));
        NewsAdapter newsAdapter = new NewsAdapter(this, mNewsType);
        mNewsAdapter = newsAdapter;
        newsAdapter.setOnItemClickListener(this);
        mDataBinding.rvNews.setAdapter(newsAdapter);
        mDataBinding.smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        mDataBinding.smartRefreshLayout.autoRefresh();
        refreshData();
    }

    private void refreshData() {
        if (isRefresh) {
            return;
        }
        isRefresh = true;
        mNewsAdapter.reqFirstPageData(new StkLoadDataCallback<NewsBean>() {
            @Override
            public void onLoadedData(boolean success, @Nullable List<NewsBean> newsBeans) {
                mDataBinding.smartRefreshLayout.finishRefresh(success);
                isRefresh = false;
            }
        });
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onItemClickCallback(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
        NewsDetailActivity.start(getContext(), (NewsBean) adapter.getItem(position));
    }

}
